﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using AllegroWebAPI.Utils;

namespace AllegroWebAPI
{
    public class MyAccountItem
    {
        public string AuctionNumber { get; set; }
        public decimal StartingPrice { get; set; }
        public decimal ItemPrice { get; set; }
        public decimal ItemReservedPrice { get; set; }
        public decimal BuyNowPrice { get; set; }
        public int Quantity { get; set; }
        public DateTime AuctionStart { get; set; }
        public DateTime AuctionEnd { get; set; }
        public string HighestBidderId { get; set; }
        public string AuctionName { get; set; }
        public int BidsCount { get; set; } // 10

        public string SellerId { get; set; }
        public int Country { get; set; }
        public string Options { get; set; }
        public string MaxAmountUserWantsPay { get; set; }
        public string MaxAmount { get; set; } // 10
        public string NotSoldItemsCount { get; set; }
        public string WonItemsCount { get; set; }
        public string BidsCount2 { get; set; } // 18
        public string ItemsSold { get; set; }
        public string ItemsNotSold { get; set; }
        public string BidderLogin { get; set; }
        public string BidderRating { get; set; }
        public string BidderCountry { get; set; }

        public string SellerLogin { get; set; }
        public string SellerRating { get; set; }
        public string SellerCountry { get; set; }

        public string WatchersCount { get; set; }
        public string HasBuyNowPrice { get; set; } // 28

        public int PhotoCount { get; set; }
        public string UserNote { get; set; }
        public string MinutesBeforeEndAuction { get; set; }
        public string FutureAuctionStatus { get; set; }
        public int DisplayCount { get; set; }
        public string ItemsFee { get; set; }
        public string Commision { get; set; }
        public string ProductId { get; set; }

    }

    public class MyAllegro : BaseAllegroExt
    {
        public class MyDataInfo
        {
            public long Id { get; set; }
            public string Login { get; set; }
            public int Rating { get; set; }
            public string Firstname { get; set; }
            public string Lastname { get; set; }
            public string Maidenname { get; set; }
            public string Company { get; set; }
            public int CountryId { get; set; }
            public int StateId{ get; set; }
            public string PostCode { get; set; }
            public string City { get; set; }
            public string Address { get; set; }
            public string Email { get; set; }
            public string Phone { get; set; }
            public string Phone2 { get; set; }
            public bool SuperSellerStatus { get; set; }
            public int SiteCountryId { get; set; }
            public bool JuniorStatus { get; set; }
            public DateTime Birthday { get; set; }
            public bool HasShop { get; set; }
            public bool CompanyIcon { get; set; }
            public bool StandardAllegro { get; set; }
            //public string InvoiceCompanyName  { get; set; }
            //public string InvoiceCompanyNip  { get; set; }
            /*  to nie koniec!!! */

            public InvoiceDataStruct InvoiceData { get; set; }
            public CompanyExtraDataStruct CompanyExtra { get; set; }
            public CompanySecondAddressStruct CompanySecondAddress { get; set; }
            public PharmacyDataStruct PharmacyData { get; set; }
            public AlcoholDataStruct AlcoholData { get; set; }
            public RelatedPersonsStruct RelatedPersons { get; set; }
        }

        public MyAllegro(AllegroClient a)
            : base(a)
        { 

        }

        private MyDataInfo mydata = null;
        
        private MyDataInfo GetMyData()
        {
            if (mydata == null)
            {
                InvoiceDataStruct ids;
                CompanyExtraDataStruct ced;
                CompanySecondAddressStruct csa;
                PharmacyDataStruct pds;
                AlcoholDataStruct ads;
                RelatedPersonsStruct rps;
                UserDataStruct u = aapi.WebService.doGetMyData(aapi.SessionHandle, out ids, out ced, out csa, out pds, out ads, out rps);

                mydata = new MyDataInfo()
                {
                    Address = u.userAddress,
                    AlcoholData = ads,
                    Birthday = ApiUtils.Unix2D(u.userBirthDate + 3600),
                    City = u.userCity,
                    Company = u.userCompany,
                    CompanyExtra = ced,
                    CompanyIcon = u.userCompanyIcon == 1,
                    CompanySecondAddress = csa,
                    CountryId = u.userCountryId,
                    Email = u.userEmail,
                    Firstname = u.userFirstName,
                    HasShop = u.userHasShop == 1,
                    Id = u.userId,
                    InvoiceData = ids,
                    JuniorStatus = u.userJuniorStatus == 1,
                    Lastname = u.userLastName,
                    Login = u.userLogin,
                    Maidenname = u.userMaidenName,
                    PharmacyData = pds,
                    Phone = u.userPhone,
                    Phone2 = u.userPhone2,
                    PostCode = u.userPostcode,
                    Rating = u.userRating,
                    RelatedPersons = rps,
                    SiteCountryId = u.siteCountryId,
                    StandardAllegro = u.userIsAllegroStandard == 1,
                    StateId = u.userStateId,
                    SuperSellerStatus = u.userSsStatus == 1

                };
            }
            return mydata;
        }

        public MyDataInfo MyData { get { return GetMyData(); /* doGetMyData */ } }

        private List<MyAccountItem> MyAccount2(string viewType, int offset, int limit)
        {
            MyAccountStruct2[] accountStructTable;
            accountStructTable = aapi.WebService.doMyAccount2(
                aapi.SessionHandle,
                viewType,
                offset,
                new long[0],        //pusta tablica typu int
                limit);

            List<MyAccountItem> ret = new List<MyAccountItem>();

            AllegroFormating af = new AllegroFormating();
            
            foreach (MyAccountStruct2 ac in accountStructTable)
            {
                ret.Add(new MyAccountItem()
                {
                    AuctionNumber = ac.myAccountArray[0],
                    StartingPrice = af.ToDecimal(ac.myAccountArray[1]),
                    ItemPrice = af.ToDecimal(ac.myAccountArray[2]),
                    ItemReservedPrice = af.ToDecimal(ac.myAccountArray[3]),
                    BuyNowPrice = af.ToDecimal(ac.myAccountArray[4]),
                    Quantity = af.ToInt(ac.myAccountArray[5]),
                    AuctionStart = af.ToDate(ac.myAccountArray[6]),
                    AuctionEnd = af.ToDate(ac.myAccountArray[7]),
                    HighestBidderId = ac.myAccountArray[8],
                    AuctionName = ac.myAccountArray[9],
                    BidsCount = af.ToInt(ac.myAccountArray[10]),// 10

                    SellerId = ac.myAccountArray[11],
                    Country = af.ToInt(ac.myAccountArray[12]),
                    Options = ac.myAccountArray[13],

                    MaxAmountUserWantsPay = ac.myAccountArray[14],
                    MaxAmount = ac.myAccountArray[15], // 10
                    NotSoldItemsCount = ac.myAccountArray[16],
                    WonItemsCount = ac.myAccountArray[17],
                    BidsCount2 = ac.myAccountArray[18], // 18
                    ItemsSold = ac.myAccountArray[19],
                    ItemsNotSold = ac.myAccountArray[20],
                    BidderLogin = ac.myAccountArray[21],
                    BidderRating = ac.myAccountArray[22],
                    BidderCountry = ac.myAccountArray[23],

                    SellerLogin = ac.myAccountArray[24],
                    SellerRating = ac.myAccountArray[25],
                    SellerCountry = ac.myAccountArray[26],

                    WatchersCount = ac.myAccountArray[27],
                    HasBuyNowPrice = ac.myAccountArray[28],


                    PhotoCount = af.ToInt(ac.myAccountArray[29]),
                    UserNote = ac.myAccountArray[30],
                    MinutesBeforeEndAuction = ac.myAccountArray[31],
                    FutureAuctionStatus = ac.myAccountArray[32],
                    DisplayCount = af.ToInt(ac.myAccountArray[33]),
                    ItemsFee = ac.myAccountArray[34],
                    Commision = ac.myAccountArray[35],
                    ProductId = ac.myAccountArray[36]

                });

            }
            return ret;
        }

        /// <summary>
        /// Metoda pozwala na pobranie listy ofert z poszczególnych zakładek Mojego Allegro (licytowane, kupione, niekupione, obserwowane: trwające, obserwowane: zakończone, sprzedawane, sprzedane, niesprzedane, do wystawienia) zalogowanego użytkownika. Domyślnie zwracanych jest pierwszych 25 ofert z danej zakładki, posortowanych malejąco po czasie ich zakończenia. Możliwe jest także pobranie informacji o konkretnych ofertach z danej zakładki (items-array). Pełen podgląd nazw oraz identyfikatorów kupujących możliwy jest tylko dla zakładek typu 'sell' i 'sold' - dla pozostałych typów wspomniane dane zwrócone zostaną w formie zanonimizowanej. Ważne! Po ręcznym usunięciu ofert z zakładek Mojego Allegro na WWW, metoda również przestanie zwracać informacje o nich. 
        /// </summary>
        /// <param name="accountType"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<MyAccountItem> MyAccount(MyAccountType accountType, int offset, int limit)
        {
            return MyAccount2(accountType.ToString(), offset, limit);
        }

        public List<MyAccountItem> MyAccount(MyAccountType accountType)
        {
            return MyAccount(accountType, 0, 100);
        }

        /// <summary>
        /// Metoda pozwala na pobranie listy ulubionych sprzedających zalogowanego użytkownika. 
        /// </summary>
        /// <returns></returns>
        public List<FavouritesSellersStruct> GetFavouriteSellers()
        {
            return aapi.WebService.doGetFavouriteSellers(aapi.SessionHandle).ToList();
        }

        /// <summary>
        /// Metoda pozwala na pobranie listy ulubionych kategorii zalogowanego użytkownika. 
        /// </summary>
        /// <returns></returns>
        public List<FavouritesCategoriesStruct> GetFavouriteCategories()
        {
            return aapi.WebService.doGetFavouriteCategories(aapi.SessionHandle).ToList();
        }


        /// <summary>
        /// Metoda odtwarza pełną funkcjonalność zakładki "Licytuję" w Moim Allegro. Dodatkowo umożliwia sortowanie oraz wyszukiwanie ofert po nazwie.
        /// </summary>
        /// <returns></returns>
        public List<BidItemStruct> GetMyBidItems(SortOptionsType sort, SortOptionsOrder sortOrder, string searchString, int categoryId, int pageSize, int pageNumber)
        {
            //return 

            SortOptionsStruct sos = new SortOptionsStruct() { sortType = (int)sort, sortOrder = (int)sortOrder };

            BidItemStruct[] ooo;
            int r = aapi.WebService.doGetMyBidItems(aapi.SessionHandle, sos, searchString, categoryId, true, null, pageSize, true, pageNumber, true, out ooo);
            return ooo.ToList();
        }

        /// <summary>
        /// Informacje o wybranych sposobach platnosci
        /// </summary>
        /// <param name="auctionIds"></param>
        /// <returns></returns>
        public List<PostBuyFormDataStruct> GetPostBuyForms(List<long> auctionIds)
        {

            long[] tranIds = aapi.WebService.doGetTransactionsIDs(aapi.SessionHandle, auctionIds.ToArray(), "seller", null);
            PostBuyFormDataStruct[] ret;
            if (tranIds.Count() > 0)
            {
                ret = aapi.WebService.doGetPostBuyFormsDataForSellers(aapi.SessionHandle, tranIds);
            }
            else
            { 
                ret = new PostBuyFormDataStruct[0];
            }


            return ret.ToList();
        }

        public List<UserIncomingPaymentStruct> GetMyIncomingPayments(DateTime from, DateTime to)
        {
            UserIncomingPaymentStruct[] ret = aapi.WebService.doGetMyIncomingPayments(aapi.SessionHandle, 0, 0, ApiUtils.D2Unix(from), ApiUtils.D2Unix(to), 25, 0);

            return ret.ToList();
        }
        
        /// <summary>
        /// Metoda pozwala na pobranie pełnych danych kontaktowych kontrahentów z danej oferty. Metoda zwraca różne dane - w zależności od tego, czy zalogowany użytkownik był sprzedającym (user-data, user-sent-to-data), czy kupującym (user-data, user-bank-accounts, company-second-address) w ramach danej oferty. W przypadku podania niepoprawnego identyfikatora oferty, zostanie dla niego zwrócona pusta struktura. 
        /// </summary>
        /// <param name="auctionIds">max 25</param>
        /// <returns></returns>
        public List<ItemPostBuyDataStruct> GetPostBuyData(List<long> auctionIds)
        {
            ItemPostBuyDataStruct[] ret = aapi.WebService.doGetPostBuyData(aapi.SessionHandle, auctionIds.ToArray());
            return ret.ToList();
        }

    }
}
